package com.jzy.secondhandbooktradingmanagement.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.secondhandbooktradingmanagement.entity.Book;
import com.jzy.secondhandbooktradingmanagement.entity.Cart;
import com.jzy.secondhandbooktradingmanagement.entity.User;
import com.jzy.secondhandbooktradingmanagement.mapper.BookMapper;
import com.jzy.secondhandbooktradingmanagement.mapper.CartMapper;
import com.jzy.secondhandbooktradingmanagement.service.ICartService;
import com.jzy.secondhandbooktradingmanagement.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private BookMapper bookMapper;

    @Override
    public void addToCart(Cart cart) {
        User currentUser = TokenUtils.getUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }

        // 检查该用户购物车中是否已存在该商品
        Cart existingCart = cartMapper.selectOne(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId, currentUser.getId())
                .eq(Cart::getBookId, cart.getBookId()));

        if (existingCart != null) {
            // 如果存在，增加数量
            existingCart.setCount(existingCart.getCount() + (cart.getCount() == null ? 1 : cart.getCount()));
            cartMapper.updateById(existingCart);
        } else {
            // 如果不存在，新增
            cart.setUserId(currentUser.getId());
            cart.setCreateTime(new Date());
            if (cart.getCount() == null) {
                cart.setCount(1);
            }
            cartMapper.insert(cart);
        }
    }

    @Override
    public void emptyCart() {
        User currentUser = TokenUtils.getUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }
        cartMapper.delete(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId, currentUser.getId()));
    }

    @Override
    public List<Cart> listCart() {
        User currentUser = TokenUtils.getUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }

        List<Cart> carts = cartMapper.selectList(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId, currentUser.getId())
                .orderByDesc(Cart::getCreateTime));

        // 填充图书信息
        for (Cart cart : carts) {
            Book book = bookMapper.selectById(cart.getBookId());
            cart.setBook(book);
        }
        return carts;
    }
}
